package com.carlinfo.shop.back.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.carlinfo.shop.common.util.ConstatFinalUtil;
import com.carlinfo.shop.common.util.PageInfoUtil;
import com.carlinfo.shop.common.web.controller.BaseController;
import com.carlinfo.shop.goods.pojo.AGoods;
import com.carlinfo.shop.goods.pojo.AGoodsBrand;
import com.carlinfo.shop.goods.pojo.AGoodsBrandEnum;
import com.carlinfo.shop.goods.pojo.AGoodsCate;
import com.carlinfo.shop.goods.service.IGoodsService;
import com.carlinfo.shop.users.pojo.AAdmins;

/**
 * 商品模块的后台Controller
 * 
 * @author wangshMac
 */
@Controller
@RequestMapping("/back/goods")
public class GoodsBackController extends BaseController
{
	@Resource
	private IGoodsService goodsService;

	/* ===== 品牌管理开始 ===== */
	/**
	 * 打开品牌列表页面
	 * 
	 * @return
	 */
	@RequestMapping("/brandList")
	public String brandList()
	{
		ConstatFinalUtil.LOGGER.info("==brandList==");
		return "/back/goods/brandList";
	}

	/**
	 * 打开品牌列表页面_专门用于取数据 参照datagrid.json这个文件
	 * 
	 * @return
	 */
	@RequestMapping(value = "/brandListJSON", produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String brandListJSON(HttpServletRequest request)
	{
		ConstatFinalUtil.LOGGER.info("==brandListJSON==");
		/* 分页模块 */
		String page = request.getParameter("page");
		String rows = request.getParameter("rows");
		PageInfoUtil pageInfoUtil = this.proccedPageInfoUtil(page, rows);
		/* 搜索模块 */
		String keyword = request.getParameter("keyword");
		String status = request.getParameter("status");
		String st = request.getParameter("st");
		String ed = request.getParameter("ed");

		if (keyword == null)
		{
			keyword = "";
		}
		keyword = keyword.trim();

		if (status == null)
		{
			status = "";
		}
		if (st == null)
		{
			st = "";
		}
		if (ed == null)
		{
			ed = "";
		}
		Date stDate = null;
		Date edDate = null;
		if (!"".equalsIgnoreCase(st) && !"".equalsIgnoreCase(ed))
		{
			/* 将字符串变成时间 */
			stDate = this.dateUtil.strToDateTime(st);
			edDate = this.dateUtil.strToDateTime(ed);
		}

		Map<String, Object> condMap = new HashMap<String, Object>();
		/* 清除map里面的内容 */
		condMap.clear();

		condMap.put("keyword", keyword);
		if (!"".equalsIgnoreCase(status))
		{
			condMap.put("status", status);
		}
		condMap.put("stDate", stDate);
		condMap.put("edDate", edDate);
		/* 调用Service的方法从数据库中取数据 */
		Map<String, Object> resultMap = this.goodsService.findCondListGoodsBrandService(pageInfoUtil, condMap);
		/* 凡是取值的时候,一定要确定一下里面是不是有值 */
		List<AGoodsBrand> brandList = (List<AGoodsBrand>) resultMap.get("goodsBrandList");
		int totalRecord = (int) resultMap.get("totalRecord");
		pageInfoUtil.setTotalRecord(totalRecord);
		/* 放到四大作用域中 */
		request.setAttribute("brandList", brandList);

		/* 拼装easyui需要的json */
		JSONObject resultJSON = new JSONObject();
		resultJSON.put("total", pageInfoUtil.getTotalRecord());
		JSONArray brandArr = new JSONArray();

		for (Iterator iterator = brandList.iterator(); iterator.hasNext();)
		{
			AGoodsBrand brand = (AGoodsBrand) iterator.next();
			/* 将pojo转换为json */
			JSONObject brandJSON = brand.toJSON();
			brandArr.add(brandJSON);
		}

		resultJSON.put("rows", brandArr);
		return resultJSON.toJSONString();
	}

	/**
	 * 打开品牌添加页面
	 * 
	 * @return
	 */
	@RequestMapping("/brandInsert")
	public String brandInsert()
	{
		ConstatFinalUtil.LOGGER.info("==brandInsert==");
		return "/back/goods/brandInsert";
	}

	/**
	 * 品牌添加提交操作
	 * 
	 * 添加是Servlet最全的代码 ~接收参数(全部是字符串) ~处理参数(将字符串变成POJO的类型) ~new对象 ~赋值 ~调用Service方法
	 * ~将Service方法执行的结果存储到四大作用域中
	 * 
	 * 交给SpringMVC的驱动(赋值) ~在方法的参数中增加一个对象 ~在表单提交的时候(参数:键=值&键=值&键=值);键=pojo的属性
	 * 
	 * @return
	 */
	@RequestMapping(value = "/brandInsertSubmit", produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String brandInsertSubmit(AGoodsBrand brand, String pubTimeStr)
	{
		ConstatFinalUtil.LOGGER.info("==brandInsertSubmit==");

		Date pubTime = this.dateUtil.strToDateTime(pubTimeStr);
		brand.setPubTime(pubTime);

		/* 手动赋值的选项 */
		brand.setCreateTime(new Date());
		brand.setUpdateTime(new Date());
		/* 调用Service方法 */
		JSONObject resDbJSON = this.goodsService.saveOneGoodsBrandService(brand);
		ConstatFinalUtil.LOGGER.info("==品牌添加返回结果=={}", resDbJSON);
		return resDbJSON.toJSONString();
	}

	/**
	 * 打开品牌更新页面
	 * 
	 * model只能放到request中
	 * 
	 * @return
	 */
	@RequestMapping("/brandUpdate")
	public String brandUpdate(String brandId, Model model)
	{
		ConstatFinalUtil.LOGGER.info("==brandUpdate==");
		/* 根据id查询品牌 */
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.clear();
		condMap.put("id", brandId);
		AGoodsBrand brand = this.goodsService.findOneGoodsBrandService(condMap);

		/* 将service查询的结果放到四大作用域中 */
		model.addAttribute("brand", brand);
		model.addAttribute("filePath", ConstatFinalUtil.SYS_CONFIG_JSON.get("path_website"));
		return "/back/goods/brandUpdate";
	}

	/**
	 * 打开品牌更新页面 千万不要使用SpringMVC里面的驱动
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/brandUpdateSubmit", produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String brandUpdateSubmit(MultipartFile file, String brandId, HttpServletRequest request) throws Exception
	{
		ConstatFinalUtil.LOGGER.info("==brandUpdateSubmit==");
		/* 根据id查询品牌 */
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.clear();
		condMap.put("id", brandId);
		AGoodsBrand brand = this.goodsService.findOneGoodsBrandService(condMap);

		/* 接收参数 */
		String name = request.getParameter("name");
		String website = request.getParameter("website");
		String status = request.getParameter("status");
		String content = request.getParameter("content");

		String pubTimeStr = request.getParameter("pubTimeStr");
		Date pubTime = this.dateUtil.strToDateTime(pubTimeStr);
		brand.setPubTime(pubTime);

		/* 赋值 */
		brand.setName(name);
		brand.setWebsite(website);
		brand.setStatus(Byte.valueOf(status));
		brand.setContent(content);
		brand.setUpdateTime(new Date());

		/* 调用Service的方法 */
		if (file != null)
		{
			request.setAttribute("filePath", ConstatFinalUtil.SYS_CONFIG_JSON.get("path.rela"));
			condMap.clear();

			/* 由于万恶的dubbo,上传文件写到Controller层 */
			String fileName = file.getOriginalFilename();
			InputStream is = file.getInputStream();

			if (!"".equalsIgnoreCase(fileName))
			{

				/* 用户点击了上传文件 */
				/*
				 * 拼装三个路径: 绝对路径: 相对路径: 网络路径:在显示的时候使用
				 */
				String webpath = ConstatFinalUtil.SYS_CONFIG_JSON.getString("path_webpath");
				String websitePath = ConstatFinalUtil.SYS_CONFIG_JSON.getString("path_website");
				String rela = ConstatFinalUtil.SYS_CONFIG_JSON.getString("path_rela");

				/*
				 * 拼装相对路径: /uploadfile/+模块名+日期+uuid.jpg
				 * 
				 * 文件名:1.jpg
				 */
				rela = rela + "/good/brand/" + this.dateUtil.dateToStr(new Date()) + "/" + UUID.randomUUID().toString()
						+ fileName.substring(fileName.lastIndexOf("."), fileName.length());
				/* 拼装本地的绝对路径 */
				webpath = webpath + rela;
				File tarFile = new File(webpath);
				if (!tarFile.getParentFile().exists())
				{
					tarFile.getParentFile().mkdirs();
				}
				FileOutputStream fos = new FileOutputStream(tarFile);

				/* 复制文件 */
				if (!this.fileUtil.copy(is, fos))
				{
					ConstatFinalUtil.LOGGER.error("上传文件失败了;目标文件是:{}", webpath);
				}

				brand.setLogoPath(rela);
			}
		}
		JSONObject resDbJSON = this.goodsService.updateOneGoodsBrandService(brand);
		return resDbJSON.toJSONString();
	}
	/* ===== 品牌管理结束 ===== */

	/* ===== 商品管理开始 ===== */
	/**
	 * 打开品牌列表页面
	 * 
	 * @return
	 */
	@RequestMapping("/goodsList")
	public String goodsList()
	{
		ConstatFinalUtil.LOGGER.info("==goodsList==");
		return "/back/goods/goodsList";
	}

	/**
	 * 打开品牌列表页面_专门用于取数据 参照datagrid.json这个文件
	 * 
	 * @return
	 */
	@RequestMapping(value = "/goodsListJSON", produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String goodsListJSON(HttpServletRequest request)
	{
		ConstatFinalUtil.LOGGER.info("==goodsListJSON==");
		/* 分页模块 */
		String page = request.getParameter("page");
		String rows = request.getParameter("rows");
		PageInfoUtil pageInfoUtil = this.proccedPageInfoUtil(page, rows);
		/* 搜索模块 */
		String keyword = request.getParameter("keyword");
		String status = request.getParameter("status");
		String st = request.getParameter("st");
		String ed = request.getParameter("ed");

		if (keyword == null)
		{
			keyword = "";
		}
		keyword = keyword.trim();

		if (status == null)
		{
			status = "";
		}
		if (st == null)
		{
			st = "";
		}
		if (ed == null)
		{
			ed = "";
		}
		Date stDate = null;
		Date edDate = null;
		if (!"".equalsIgnoreCase(st) && !"".equalsIgnoreCase(ed))
		{
			/* 将字符串变成时间 */
			stDate = this.dateUtil.strToDateTime(st);
			edDate = this.dateUtil.strToDateTime(ed);
		}

		Map<String, Object> condMap = new HashMap<String, Object>();
		/* 清除map里面的内容 */
		condMap.clear();

		condMap.put("keyword", keyword);
		if (!"".equalsIgnoreCase(status))
		{
			condMap.put("status", status);
		}
		condMap.put("stDate", stDate);
		condMap.put("edDate", edDate);
		/* 调用Service的方法从数据库中取数据 */
		Map<String, Object> resultMap = this.goodsService.findCondListGoodsService(pageInfoUtil, condMap);
		/* 凡是取值的时候,一定要确定一下里面是不是有值 */
		List<AGoods> goodsList = (List<AGoods>) resultMap.get("list");
		int totalRecord = (int) resultMap.get("totalRecord");
		pageInfoUtil.setTotalRecord(totalRecord);
		/* 放到四大作用域中 */
		request.setAttribute("goodsList", goodsList);

		/* 拼装easyui需要的json */
		JSONObject resultJSON = new JSONObject();
		resultJSON.put("total", pageInfoUtil.getTotalRecord());
		JSONArray goodsArr = new JSONArray();

		for (Iterator iterator = goodsList.iterator(); iterator.hasNext();)
		{
			AGoods goods = (AGoods) iterator.next();
			/* 将pojo转换为json */
			JSONObject goodsJSON = goods.toJSON();
			goodsArr.add(goodsJSON);
		}

		resultJSON.put("rows", goodsArr);
		return resultJSON.toJSONString();
	}

	/**
	 * 打开商品添加页面
	 * 
	 * @return
	 */
	@RequestMapping("/goodsInsert")
	public String goodsInsert(Model model)
	{
		ConstatFinalUtil.LOGGER.info("==goodsInsert==");
		Map<String, Object> condMap = new HashMap<String, Object>();

		/* 查询所有启用的品牌 */
		condMap.clear();
		condMap.put("status", AGoodsBrandEnum.STATUS_ENABLE.getStatus());
		Map<String, Object> resultMap = this.goodsService.findCondListGoodsBrandService(null, condMap);
		List<AGoodsBrand> brandList = (List<AGoodsBrand>) resultMap.get("goodsBrandList");

		/* 查询树形结构的分类 */
		List<AGoodsCate> cateList = this.goodsService.findTreeListGoodsCateService();

		/* 存储四大作用域 */
		model.addAttribute("brandList", brandList);
		model.addAttribute("cateList", cateList);
		return "/back/goods/goodsInsert";
	}

	/**
	 * 商品添加提交操作
	 * 
	 * 添加是Servlet最全的代码 ~接收参数(全部是字符串) ~处理参数(将字符串变成POJO的类型) ~new对象 ~赋值 ~调用Service方法
	 * ~将Service方法执行的结果存储到四大作用域中
	 * 
	 * 交给SpringMVC的驱动(赋值) ~在方法的参数中增加一个对象 ~在表单提交的时候(参数:键=值&键=值&键=值);键=pojo的属性
	 * 
	 * @return
	 */
	@RequestMapping(value = "/goodsInsertSubmit", produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String goodsInsertSubmit(HttpServletRequest request, AGoods goods, String pubTimeStr)
	{
		ConstatFinalUtil.LOGGER.info("==goodsInsertSubmit==");
		Map<String, Object> condMap = new HashMap<String, Object>();

		/* 保存管理员 */
		HttpSession session = request.getSession();
		AAdmins admins = (AAdmins) session.getAttribute("admins");
		/* 设置创建人id */
		goods.setAdminsId(admins.getId());

		Date pubTime = this.dateUtil.strToDateTime(pubTimeStr);
		goods.setPubTime(pubTime);

		/*
		 * 用户选择了哪些规格项 期望的结果是:分类对应的规格项,其中最里面的values由数组变成值
		 * 
		 * 以分类的规格(JSON)为蓝本;只修改里面的规格选项
		 */
		/* 先根据分类id查询出分类 */
		condMap.clear();
		condMap.put("id", goods.getCateId());
		AGoodsCate goodsCate = this.goodsService.findOneGoodsCateService(condMap);
		/* 取出分类模板的规格 */
		JSONArray specArr = goodsCate.getSpecArr();
		if (specArr != null)
		{
			for (Iterator iterator = specArr.iterator(); iterator.hasNext();)
			{
				JSONObject cateTempJSON = (JSONObject) iterator.next();
				/* 取到所有的键 */
				JSONArray keysArr = cateTempJSON.getJSONArray("keys");
				for (Iterator iterator2 = keysArr.iterator(); iterator2.hasNext();)
				{
					JSONObject keyTempJSON = (JSONObject) iterator2.next();
					/*
					 * 值填写多少 值要从页面上获取
					 */
					String paramKey = "specVal_" + cateTempJSON.getString("name") + "_" + keyTempJSON.getString("name");
					String values = request.getParameter(paramKey);
					ConstatFinalUtil.LOGGER.info("-前面页面取的键:{},值:{}", paramKey, values);
					keyTempJSON.put("values", values);
				}
			}
			/* 设置商品的规格 */
			goods.setSpec(specArr.toJSONString());
		}

		/* 手动赋值的选项 */
		goods.setCreateTime(new Date());
		goods.setUpdateTime(new Date());
		/* 调用Service方法 */
		JSONObject resDbJSON = this.goodsService.saveOneGoodsService(goods);
		ConstatFinalUtil.LOGGER.info("==商品添加返回结果=={}", resDbJSON);
		return resDbJSON.toJSONString();
	}

	/**
	 * 打开商品更新页面
	 * 
	 * model只能放到request中
	 * 
	 * @return
	 */
	@RequestMapping("/goodsUpdate")
	public String goodsUpdate(String goodsId, String operType, Model model)
	{
		ConstatFinalUtil.LOGGER.info("==goodsUpdate==");
		/* 根据id查询商品 */
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.clear();
		condMap.put("id", goodsId);
		AGoods goods = this.goodsService.findOneGoodsService(condMap);
		/* 将service查询的结果放到四大作用域中 */
		model.addAttribute("goods", goods);
		model.addAttribute("filePath", ConstatFinalUtil.SYS_CONFIG_JSON.get("path_website"));

		if ("update".equalsIgnoreCase(operType))
		{
			/* 更新 */
			/* 查询所有启用的品牌 */
			condMap.clear();
			condMap.put("status", AGoodsBrandEnum.STATUS_ENABLE.getStatus());
			Map<String, Object> resultMap = this.goodsService.findCondListGoodsBrandService(null, condMap);
			List<AGoodsBrand> brandList = (List<AGoodsBrand>) resultMap.get("goodsBrandList");

			/* 查询树形结构的分类 */
			List<AGoodsCate> cateList = this.goodsService.findTreeListGoodsCateService();

			/* 存储四大作用域 */
			model.addAttribute("brandList", brandList);
			model.addAttribute("cateList", cateList);

			return "/back/goods/goodsUpdate";
		}
		return "/back/goods/goodsInfo";
	}

	/**
	 * 打开商品更新页面 千万不要使用SpringMVC里面的驱动
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/goodsUpdateSubmit", produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String goodsUpdateSubmit(MultipartFile file, String goodsId, HttpServletRequest request) throws Exception
	{
		ConstatFinalUtil.LOGGER.info("==goodsUpdateSubmit==");
		/* 根据id查询商品 */
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.clear();
		condMap.put("id", goodsId);
		AGoods goods = this.goodsService.findOneGoodsService(condMap);

		/* 接收参数 */
		String cateId = request.getParameter("cateId");
		String brandId = request.getParameter("brandId");
		String name = request.getParameter("name");
		String title = request.getParameter("title");
		String url = request.getParameter("url");
		String weight = request.getParameter("weight");
		String remainNum = request.getParameter("remainNum");
		String marketPrice = request.getParameter("marketPrice");
		String price = request.getParameter("price");
		String status = request.getParameter("status");
		String content = request.getParameter("content");

		String pubTimeStr = request.getParameter("pubTimeStr");
		Date pubTime = this.dateUtil.strToDateTime(pubTimeStr);
		goods.setPubTime(pubTime);

		/*
		 * 规格 如果分类不一样,那规格肯定变了
		 */
		goods.setCateId(Integer.valueOf(cateId));

		/*
		 * 用户选择了哪些规格项 期望的结果是:分类对应的规格项,其中最里面的values由数组变成值
		 * 
		 * 以分类的规格(JSON)为蓝本;只修改里面的规格选项
		 */
		/* 先根据分类id查询出分类 */
		condMap.clear();
		condMap.put("id", goods.getCateId());
		AGoodsCate goodsCate = this.goodsService.findOneGoodsCateService(condMap);
		/* 取出分类模板的规格 */
		JSONArray specArr = goodsCate.getSpecArr();
		if (specArr != null)
		{
			for (Iterator iterator = specArr.iterator(); iterator.hasNext();)
			{
				JSONObject cateTempJSON = (JSONObject) iterator.next();
				/* 取到所有的键 */
				JSONArray keysArr = cateTempJSON.getJSONArray("keys");
				for (Iterator iterator2 = keysArr.iterator(); iterator2.hasNext();)
				{
					JSONObject keyTempJSON = (JSONObject) iterator2.next();
					/*
					 * 值填写多少 值要从页面上获取
					 */
					String paramKey = "specVal_" + cateTempJSON.getString("name") + "_" + keyTempJSON.getString("name");
					String values = request.getParameter(paramKey);
					ConstatFinalUtil.LOGGER.info("-前面页面取的键:{},值:{}", paramKey, values);
					keyTempJSON.put("values", values);
				}
			}
			/* 设置商品的规格 */
			goods.setSpec(specArr.toJSONString());
		}

		/* 赋值 */
		goods.setName(name);
		goods.setBrandId(Integer.valueOf(brandId));
		goods.setTitle(title);
		goods.setUrl(url);
		goods.setWeight(Double.valueOf(weight));
		goods.setRemainNum(Integer.valueOf(remainNum));
		goods.setMarketPrice(Double.valueOf(marketPrice));
		goods.setPrice(Double.valueOf(price));
		goods.setStatus(Byte.valueOf(status));
		goods.setContent(content);
		goods.setUpdateTime(new Date());

		/* 调用Service的方法 */
		if (file != null)
		{
			request.setAttribute("filePath", ConstatFinalUtil.SYS_CONFIG_JSON.get("path.rela"));
			condMap.clear();

			/* 由于万恶的dubbo,上传文件写到Controller层 */
			String fileName = file.getOriginalFilename();
			InputStream is = file.getInputStream();

			if (!"".equalsIgnoreCase(fileName))
			{

				/* 用户点击了上传文件 */
				/*
				 * 拼装三个路径: 绝对路径: 相对路径: 网络路径:在显示的时候使用
				 */
				String webpath = ConstatFinalUtil.SYS_CONFIG_JSON.getString("path_webpath");
				String websitePath = ConstatFinalUtil.SYS_CONFIG_JSON.getString("path_website");
				String rela = ConstatFinalUtil.SYS_CONFIG_JSON.getString("path_rela");

				/*
				 * 拼装相对路径: /uploadfile/+模块名+日期+uuid.jpg
				 * 
				 * 文件名:1.jpg
				 */
				rela = rela + "/good/goods/" + this.dateUtil.dateToStr(new Date()) + "/" + UUID.randomUUID().toString()
						+ fileName.substring(fileName.lastIndexOf("."), fileName.length());
				/* 拼装本地的绝对路径 */
				webpath = webpath + rela;
				File tarFile = new File(webpath);
				if (!tarFile.getParentFile().exists())
				{
					tarFile.getParentFile().mkdirs();
				}
				FileOutputStream fos = new FileOutputStream(tarFile);

				/* 复制文件 */
				if (!this.fileUtil.copy(is, fos))
				{
					ConstatFinalUtil.LOGGER.error("上传文件失败了;目标文件是:{}", webpath);
				}

				goods.setListImgPath(rela);
			}
		}
		JSONObject resDbJSON = this.goodsService.updateOneGoodsService(goods);
		return resDbJSON.toJSONString();
	}
	/* ===== 商品管理结束 ===== */
}
